/* eslint-disable no-param-reassign */
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { UserStoreState, UserInfoState, UserInfoWithTokenState } from './interface';

const AUTH_LOCALESTORE_KEY = 'AUTH';

const initialState: UserStoreState = {
    auth:
        typeof localStorage.getItem(AUTH_LOCALESTORE_KEY) === 'string'
            ? JSON.parse(localStorage.getItem(AUTH_LOCALESTORE_KEY) || 'null')
            : undefined,
};

const userState = createSlice({
    name: 'userState',
    initialState,
    reducers: {
        /**
         * 当有token时，同步当前用户的信息
         */
        syncAuthState(state, action: PayloadAction<UserInfoWithTokenState>) {
            state.auth = action.payload;
            localStorage.setItem(AUTH_LOCALESTORE_KEY, JSON.stringify(action.payload));
        },
        /**
         * 同步登录权限信息
         */
        syncCurrentUserState(state, action: PayloadAction<UserInfoState>) {
            state.userinfo = action.payload;
        },
    },
});

export const { syncAuthState, syncCurrentUserState } = userState.actions;

export default userState.reducer;
